import axios from 'axios'
// import qs from 'qs'
import { Message, Loading } from 'element-ui' 
import router from '../router'
import { md5 } from '../md5/md5'
// 创建axios实例
// const baseURL = 'https://51zd.com.cn:16666'
const baseURL = 'https://gateway.supercanteen.com.cn'
// const baseURL = 'https://193.112.118.243:10001'

var headerSign = ''
const service = axios.create({
    baseURL: baseURL,
    timeout: 15000 // 请求超时时间
}) 
let bool = false;
var userInfo = {};
service.interceptors.request.use(config => {
    let timestamp = parseInt(new Date().getTime() / 1000);
    headerSign = md5(getheaderSign(config.url, config.data,timestamp)).toUpperCase();
    // if (localStorage.hj_userInfo) {
    //     try {
    //         userInfo = JSON.parse(localStorage.hj_userInfo);
    //     } catch (err) {
    //         userInfo = {};
    //     }
    // }
    config.headers["X-source"] = 'web';
    config.headers["X-timestamp"] = timestamp;
    config.headers["X-version"] = '1.0';
    config.headers["Content-Type"] = 'application/json';
    config.headers["X-sign"] = headerSign;
    // config.headers.Authorization = (localStorage.hj_userInfo && JSON.parse(localStorage.hj_userInfo).jwt) || '';
    return config
},error => {
    Message({
        message: "系统错误，请联系管理员！",
        type: 'error',
        duration: 3 * 1000
    })
    return Promise.resolve(error)
}

)
service.interceptors.response.use(
    function (response) {
        //请求正常则返回
        return Promise.resolve(response)
    },
    function (error) {
        return Promise.reject(error)
    }
);
export function baseFetchData (url, params, method) {
    return new Promise((resolve, reject) => {
        service[method](url, params)
            .then(response => {
                let res = response.data;
                if (res.resultCode == 0) {
                    resolve(res);
                }
                else if (res.resultCode == 1001 || res.resultCode == 1100 || res.resultCode == 1006) {
                    if(bool){
                        return
                    }else{
                        bool = !bool;
                    } 
                    Message({
                        message: "您暂未登录,请您先登录",
                        type: 'error',
                        duration: 2 * 1000
                    })
                    sessionStorage.storeUrl = window.location.href;
                    router.push('/login');
                    setTimeout(()=>{
                        bool = false;
                    },3000)
                    return 
                }
                else {
                    if (url == "/sitecount/v1/visit") { return }
                    // Message({
                    //     message: "res.description",
                    //     type: 'error',
                    //     duration: 3 * 1000
                    // })
                    reject(res.description);
                }
            }, err => {
                reject('网络链接失败,请稍候再试...');
            })
            .catch((error) => {
                reject('网络链接失败,请稍候再试...')
            })
    });
}



export function getParam (params) {
    var keys = [];
    var paramList = [];
    for (var key in params) {
        if(params[key]===0){
            params[key] = "0";
        }
        if(!params[key]){
            continue ;
        }
        keys.push(key);
    }
    keys = keys.sort(); //排序
    for (var i = 0; i < keys.length; i++) {
        var tempKey = keys[i];
        params[tempKey] = params[tempKey] ? params[tempKey] : "";
        paramList.push(tempKey + '=' + params[tempKey]);
    }
    return paramList.join('&');
}

export function getheaderSign (url, body,timestamp) { 
    var params = {
        'X-source': 'web',
        'X-timestamp': timestamp,
        'X-version': '1.0'
    };
    // var userInfo = {};
    // if (localStorage.hj_userInfo) {
    //     try {
    //         userInfo = JSON.parse(localStorage.hj_userInfo);
    //     } catch (err) {
    //         userInfo = {};
    //     }
    // }
    // if (userInfo.jwt) {
    //     params.Authorization = userInfo.jwt;
    // }
    var lg = getParam(params);
    var sign = url + "?" + lg + "&X-apiKey=e1e499e5746f90191ec5261947055e0c";
    
    if (JSON.stringify(body) !== '{}') {
        body = getParam(body); 
        sign += "&bodySign=" + md5(body).toUpperCase();
    }  
    return sign;
}


export function fetchData (url, params, method, callback, failure) {
    baseFetchData(url, params, method).then(res => {
        if (callback != undefined && callback != null) {
            callback(res)
        }
    }, error => {
        // Toast(error);
        if (failure != undefined && failure != null) {
            failure(error)
        } else {
            if (error && error != '') {
                Message({
                    message: error,
                    type: 'error',
                    duration: 3 * 1000
                })
            }
        }
    });
}


//图片上传先压缩
export function uploadFile(url,params,callback) {
        console.log(params);  
        let file = params.files[0] ;
        console.log(file)
         if (!file || !window.FileReader) return;  
         if (/^image/.test(file.type)) {  
             // 创建一个reader  
             let reader = new FileReader();  
            // 将图片2将转成 base64 格式  
            reader.readAsDataURL(file);  
            // 读取成功后的回调  
            reader.onloadend = function () {  
                let result = this.result;  
                let img = new Image();  
                img.src = result;  
                //判断图片是否大于1000K,否就直接上传，反之压缩图片  
                if (result <= (1000 * 1024)) { 
                    upImgFront(url,params,callback);
                }else {  
                    img.onload = function () {  
                        let src = compress(img);
                        let obj = {
                            files:[
                                dataURLtoFile(src)
                            ]
                        }
                        console.log(obj)
                        upImgFront(url,obj,callback);
                    }  
                }  
            }   
        }  
   
    }
    function dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], new Date().getTime()+'.png', { type: 'image/png' });
      }
function compress(img) {
         let canvas = document.createElement("canvas");  
         let ctx = canvas.getContext('2d');  
             //瓦片canvas  
         let tCanvas = document.createElement("canvas");  
         let tctx = tCanvas.getContext("2d");  
         let width = img.width;  
         let height = img.height;  
         //如果图片大于四百万像素，计算压缩比并将大小压至400万以下  
         let ratio;  
         if ((ratio = width * height / 4000000) > 1) {  
             console.log("大于400万像素")  
             ratio = Math.sqrt(ratio);  
             width /= ratio;  
             height /= ratio;  
         } else {  
             ratio = 1;  
         }  
         canvas.width = width;  
         canvas.height = height;  
     //        铺底色  
         ctx.fillStyle = "#fff";  
         ctx.fillRect(0, 0, canvas.width, canvas.height);  
         //如果图片像素大于100万则使用瓦片绘制  
         let count;  
         if ((count = width * height / 1000000) > 1) {  
             console.log("超过100W像素");  
             count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片  
     //            计算每块瓦片的宽和高  
             let nw = ~~(width / count);  
             let nh = ~~(height / count);  
             tCanvas.width = nw;  
             tCanvas.height = nh;  
             for (let i = 0; i < count; i++) {  
             for (let j = 0; j < count; j++) {  
                 tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);  
                 ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);  
             }  
             }  
         } else {  
             ctx.drawImage(img, 0, 0, width, height);  
         }  
         //进行最小压缩  
         let ndata = canvas.toDataURL('image/jpeg', 0.3);  
       tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;  
         return ndata;  
     }

//上传文件
export function upImgFront(url,params,callback){ 
    let timestamp = parseInt(new Date().getTime() / 1000);
    var forms = new FormData();
    const headerSign = md5(getheaderSign(url, {},timestamp)).toUpperCase();
    
    var configs = {
        headers:{
            'Content-Type':'multipart/form-data',
            'X-source': 'web',
            'X-timestamp': timestamp, 
            'X-version': '1.0',
            "X-sign":headerSign, 
        }
    };
    // configs.headers.Authorization = (localStorage.hj_userInfo && JSON.parse(localStorage.hj_userInfo).jwt) || '';
    forms.append('file',params.files[0]); 
    let loading = Loading.service({
        lock: true,
        text: '上传中……',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    // setTimeout(()=>{
    //     loading.close();
    // },8000)
    configs.timeout = 15000;
    axios.post(baseURL + url,forms ,configs).then(res=>{
        loading.close(); 
        if(!res.data || res.data.resultCode!=0){
            return Message({
                message: "上传失败",
                type: 'error',
                duration: 1 * 1000
            })
        }
        callback(res)
    }).catch(res=>{
        console.log(res);
        loading.close(); 
        return Message({
            message: "网络错误,上传失败",
            type: 'error',
            duration: 1 * 1000
        })
    }) 
}
